import { ItemStack } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent } from "@sapi-game/main";
import { RandomUtils } from "@sapi-game/utils";
import { EffectIds } from "@sapi-game/utils/vanila-data";
import { pixelPartyPlayer } from "../module";
import { PixelPartyMainState } from "../states/mainState";

interface PixelPartyItem {
    weight: number;
    func: (p: pixelPartyPlayer) => void;
}

const items: PixelPartyItem[] = [
    {
        weight: 35,
        func(p) {
            p.addEffect(EffectIds.Speed, 100, 2);
        },
    },
    {
        weight: 35,
        func(p) {
            p.addEffect(EffectIds.JumpBoost, 100, 2);
        },
    },
    {
        weight: 20,
        func(p) {
            p.addEffect(EffectIds.Invisibility, 60, 1, true);
        },
    },
    {
        weight: 10,
        func(p) {
            p.relifeTimes++;
            p.sendMessage("你获得了一张复活卡");
        },
    },
];

/**道具管理 */
export class PixelPartyItemManager extends GameComponent<PixelPartyMainState> {
    private readonly itemTag = "PixelPartyItem";

    override onAttach(): void {
        this.subscribe(Game.events.interval, () => {
            this.context.players.forEach((p) => {
                if (!p.alive) return;
                const entites = Dimensions.Overworld.getEntities({
                    location: p.player.location,
                    maxDistance: 3,
                    type: "minecraft:item",
                    tags: [this.itemTag],
                });
                if (entites.length == 0) return;
                entites.forEach((e) => e.remove());
                this.randomItem(p);
            });
        });
    }

    loadItems(cnt: number) {
        const volume = this.context.map.volume.toVolume();
        const min = volume.getMin();
        const max = volume.getMax();
        const item = new ItemStack("beacon");
        for (let i = 0; i < cnt; i++) {
            const pos = {
                x: RandomUtils.intRange(min.x, max.x + 1),
                y: min.y + 1,
                z: RandomUtils.intRange(min.z, max.z + 1),
            };
            const entity = Dimensions.Overworld.spawnItem(item, pos);
            entity.addTag(this.itemTag);
        }
    }

    randomItem(p: pixelPartyPlayer) {
        if (!p.player) return;
        const item = RandomUtils.weightedChoice(
            items,
            items.map((i) => i.weight)
        );
        item?.func(p);
    }

    rmItems() {
        const items = Dimensions.Overworld.getEntities({
            tags: [this.itemTag],
        });
        items.forEach((i) => i.remove());
    }

    override onDetach(): void {
        this.rmItems();
    }
}
